--!native
RStorage = game.ReplicatedStorage;
local sharedLibs = RStorage.SharedLibs;
local pt = require(sharedLibs.Prototype);
Vec2 = require(sharedLibs.Math.Vec2);

--[[
	Matrix 2x2
]]
local Mat2 = pt.proto();

-- 创建新的mat2对象
function Mat2:constructor(m11, m12, m21, m22)
    local m = self;
    m[1] = m11 or 0
    m[2] = m12 or 0
    m[3] = m21 or 0
    m[4] = m22 or 0
end

----
-- 创建旋转矩阵
function Mat2.ByAngle(angle)
    local cosAngle = math.cos(angle)
    local sinAngle = math.sin(angle)
    return Mat2.new(
        cosAngle, -sinAngle,
        sinAngle, cosAngle)
end

----
-- 将mat2转换为字符串
function Mat2:tostring()
    return string.format("[%f, %f]\n[%f, %f]", self[1], self[2], self[3], self[4])
end

-- 将mat2相加
function Mat2:Add(other)
    return Mat2.new(
        self[1] + other[1], self[2] + other[2],
        self[3] + other[3], self[4] + other[4])
end

-- 将mat2相减
function Mat2:Sub(other)
    return Mat2.new(
        self[1] - other[1], self[2] - other[2],
        self[3] - other[3], self[4] - other[4])
end

function Mat2:MulVec2(v2)
	return Vec2.new(
		self[1] * v2.x + self[2] * v2.y,
		self[3] * v2.x + self[4] * v2.y);
end

-- 和另外一个Mat2相乘
function Mat2:Mul(other)
    return Mat2.new(
            self[1] * other[1] + self[2] * other[3],
            self[1] * other[2] + self[2] * other[4],
            self[3] * other[1] + self[4] * other[3],
            self[3] * other[2] + self[4] * other[4])
end

-- 比较两个mat2是否相等
function Mat2:Equal(other)
    return self[1] == other[1] and
           self[2] == other[2] and
           self[3] == other[3] and
           self[4] == other[4]
end

-- 计算mat2的行列式
function Mat2:Determinant()
    return self[1] * self[4] - self[2] * self[3]
end

-- 计算mat2的逆矩阵
function Mat2:Inverse()
    local det = self:Determinant()
    if det == 0 then
        error("cannot invert singular matrix")
    end
    return Mat2.new(
        self[4] / det, -self[2] / det,
        -self[3] / det, self[1] / det)
end

-- 创建单位矩阵
function Mat2.Identity()
    return Mat2.new(1, 0, 0, 1)
end


return Mat2;